<template>
  <div class="notify-bar-wrapper" v-if="show">
    <div class="notify-bar">
      <img class="icon-warn" src="~@/assets/icons/attention.png" />
      <div class="message">
        <div class="animate" :style="{animationDuration: animationDuration}">
          {{ message }}
        </div>
      </div>
      <a-icon type="close" @click="close"/>
    </div>
  </div>
</template>

<script>
import { getLatestNotify, closeNotify } from '@/api/system/notify'
export default {
  name: 'NotifyBar',
  data () {
    return {
      show: false,
      timer: null,
      delayTimer: null,
      message: '',
      animationDuration: ''
    }
  },
  mounted () {
    this.init()
  },
  destroyed () {
    if (this.timer) {
      clearInterval(this.timer)
      this.timer = null
    }
    if (this.delayTimer) {
      clearTimeout(this.delayTimer)
      this.delayTimer = null
    }
  },
  methods: {
    init () {
      this.getNotify()
      this.timer = setInterval(() => {
        this.getNotify()
      }, 20 * 1000)
    },
    getNotify () {
      getLatestNotify().then(res => {
        if (res) {
          this.show = true
          this.message = res.title
          const isNew = this.id !== res.proMessageNotifyId
          this.id = res.proMessageNotifyId
          this.delayClose(isNew)
          this.setAnimationDuration()
        } else {
          this.show = false
          this.message = ''
          this.id = null
        }
      })
    },
    setAnimationDuration () {
      this.animationDuration = 10 + this.message.length * 0.2 + 's'
    },
    delayClose (isNew) {
      const duration = 30 * 6 * 1000
      if (this.delayTimer) {
        if (isNew) {
          clearTimeout(this.delayTimer)
          this.delayTimer = setTimeout(() => {
            this.close()
          }, duration)
        }
      } else {
        this.delayTimer = setTimeout(() => {
          this.close()
        }, duration)
      }
    },
    close () {
      closeNotify({
        proMessageNotifyId: this.id
      }).then(res => {
        this.show = false
        if (this.delayTimer) {
          clearTimeout(this.delayTimer)
          this.delayTimer = null
        }
      })
    }
  }
}
</script>

<style lang="less" scoped>
.notify-bar-wrapper{
  width: 100%;
  height: 38px;
}
.notify-bar{
  width:100%;
  height: 38px;
  background: #FFF9EE;
  position:fixed;
  top:64px;
  left:0;
  right: 0;
  z-index: 999;
  font-weight: 400;
  font-size: 14px;
  line-height: 38px;
  color: #687991;
  padding:0 16px;
  display: flex;
  align-items: center;
  .message{
    flex: 1;
    margin:0 12px;
    overflow: hidden;
    &:hover {
      .animate {
        animation-play-state: paused;
      }
    }
  }
}

.animate{
  width: auto;
  display: inline-block;
  white-space: nowrap;
  animation: loop linear infinite normal;
  height: 100%;
  line-height: 38px;
}

@keyframes loop{
  0%{
    transform: translateX(0);
  }
  100%{
    transform: translateX(-100%);
  }
}

</style>
